<template>
  <div class="pie-box" :id="chartId"></div>
</template>
<script setup lang="ts">
/**
 * set:(配置项){
 **************legend:(){type:,top:,left:,right:,bottom:,}
 **************series:(){top:,left:,right:,bottom:,}
 * }
 * data:(图表数据)
 * xData:X轴数据
 * chartId:(表格ID:'String')
 * title:表格头部名称
 */
import echarts from "@/plugins/echarts";
import {
  nextTick,
  onBeforeUnmount,
  onMounted,
  reactive,
  ref,
  watch
} from "vue";
interface DataItemType {
  title: string
  value: number
  [key: string]: any
}
interface SeriesItemType {
  title: string
  color?: string
  colorList?: string[]
}
let myChart: echarts | null = null
const props = withDefaults(defineProps<{
  data: Array<DataItemType> | DataItemType[][]
  series: Array<SeriesItemType> | SeriesItemType[][]
  xAxis?: string[]
  showLegend?: boolean,
  chartId: string,
  title?: string
}>(), {
  showLegend: true,
})
let option = {
  legend: {
    show: props.showLegend,
    top: "auto",
    right: "45%",
    itemGap: 10,
    itemWidth: 8,
    itemHeight: 8,
    pageButtonItemGap: 5,
    textStyle: {
      fontSize: 12,
      color: "#313233",
    },
  },
  grid: {
    left: 30,
    right: 30,
    bottom: 10,
    containLabel: true,
  },
  tooltip: {
    trigger: 'axis',
    backgroundColor: '#333',
    confine: true,
    textStyle: {
      color: '#fff',
      fontSize: '14',
      fontFamily: 'Microsoft YaHei',
    },
    className: 'echarts-tooltip-dark',
  },
  series: [
    {
      name: "",
      type: "line",
      showSymbol: false,
      data: [] as null | number[] | undefined,
      smooth: true,
      color: "#4673e9",
    }
  ],
  xAxis: {
    type: "category",
    splitNumber: 6,
    boundaryGap: false,
    data: [] as null | string[] | undefined,
    nameGap: 22,
    axisLabel: { //坐标轴刻度标签的相关设置。
      show: true,
      padding: [6, 16, 10, 0],
      fontSize: 14,
      showMinLabel: true,
      showMaxLabel: true,
      hideOverlap: false,
      interval: 'auto',
      color: '#333',
      formatter: function (value, index) {
        if (action.timeType === 1) {
          const param = value.split(' ')
          // if (option.xAxis.data.length < 200 && param[1] === '00:00') {
          //   return param[1] + '\n' + param[0]
          // }
          return param[1]
        } else if (action.timeType === 2 && value.length > 12) {
          const param = value.split(' ')
          return param[0]
        }
        return value
      }
    },
    axisLine: {// 坐标线
      lineStyle: {
        type: 'dashed',
        color: '#333',
        width: 1,
      },
    },
  },
  yAxis: {
    type: "value",
    nameLocation: "start",
    nameTextStyle: {
      color: "#2c3542",
      align: "right",
      verticalAlign: "top",
    },
    nameGap: 22,
  },
};

const echartsResize = () => {
  myChart?.resize()
}
const loading = ref(false)
watch(() => loading.value, (newValue) => {
  nextTick(() => {
    if (newValue) {
      myChart?.showLoading({
        text: '',
        color: '#4a9cfb',
        maskColor: 'rgba(255, 255, 255, 0.5)',
        opacity: 0.4,
        spinnerRadius: 8,
        lineWidth: 2,//转动画（spinner）的线宽
      })
    } else {
      myChart?.hideLoading()
    }
  })
}, { deep: true })
const action = reactive({
  // 1 分钟or小时 ,2天 ,3月
  timeType: 2,
  //1只包含天,月  2 分 ,小时,天
  echartsType: 1
})
const ininEcharts = () => {
  if (!myChart) {
    myChart = echarts.getInstanceByDom(document.querySelector('#' + props.chartId));
    myChart = echarts.init(document.getElementById(props.chartId));
  }

}
//生命周期
onMounted(() => {
  ininEcharts()
  nextTick(() => {
    myChart?.resize()
  })

  window.addEventListener("resize", echartsResize, false);
})
onBeforeUnmount(() => {
  myChart?.dispose()
  console.log('unonmo', myChart);
  window.removeEventListener("resize", echartsResize, false);
});
watch(
  () => props,
  () => {
    nextTick(() => {
      // 每次初始化
      option.series = [{
        name: "",
        type: "line",
        showSymbol: false,
        data: [],
        smooth: true,
        color: "#4673e9",
      }]
      option.xAxis.axisLabel.interval = 'auto'
      option.xAxis.data = []
      if (!(props.data[0] instanceof Array)) {
        option.series[0].name = props.series[0] ? (props.series[0] as SeriesItemType).title : ''
        option.series[0].data = props.data?.map(item => item.value)
        option.xAxis.data = props.data?.map(item => item.title)
        option.series[0].color = props.series[0] && ((props.series[0] as SeriesItemType).color || '')
        if (props.series[0] && (props.series[0] as SeriesItemType)?.colorList) {
          //@ts-ignore
          option.series[0].areaStyle = {
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [
                { offset: 0, color: props.series[0]?.colorList[0] },
                { offset: 1, color: props.series[0]?.colorList[1] }
              ]
            )
          }
        }
      } else {
        option.xAxis.data = props.xAxis
        props.series.forEach((item, index) => {
          let seriesObj = {
            type: "line",
            smooth: true,
            showSymbol: false,
          } as any
          seriesObj.name = item.title
          seriesObj.data = props.data[index]

          if (item.color) {
            seriesObj.color = item.color
          }
          //@ts-ignore
          seriesObj.areaStyle = {
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [
                { offset: 0, color: props.series[index]?.colorList[0] },
                { offset: 1, color: props.series[index]?.colorList[1] }
              ]
            )
          }
          option.series[index] = seriesObj
        });
      }

      option.yAxis?.axisLabel && delete option.yAxis?.axisLabel
      delete option.tooltip.formatter
      console.log(option, myChart, 'update');
      ininEcharts()
      myChart?.setOption(option, true);
    })

  }, { deep: true, immediate: true }
);
defineExpose({
  loading,
  action
})

</script>
<style lang="scss" scoped>
.pie-box {
  width: 100%;
  height: 100%;

}
</style>
